import { HttpParams } from '@angular/common/http';
import { ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { _HttpClient } from '@delon/theme';
import { NzMessageService } from 'ng-zorro-antd/message';

@Component({
  selector: 'app-business-inbound-plan',
  templateUrl: './inbound-plan.component.html'
})
export class BusinessInboundPlanComponent implements OnInit {
  loading = true;
  q: {
    shopId: number; // 店铺ID
    companyId: number; // 店铺ID
    planStatus: number; // 状态
    fulfillmentCenterId: string; // 履约中心
    planId: string; // 计划编号
    skuId: string; // skuid
  } = {
    shopId: 0,
    companyId: 0,
    planStatus: 0,
    fulfillmentCenterId: '',
    planId: '',
    skuId: ''
  };
  url = `api/inbound_plans`;
  total = 0;
  pi = 1;
  ps = 15;
  listOfData = [];
  shops = [];
  shopMap = {};

  shipmentStatusOptionTags = {
    '1': { text: '商家处理中', color: 'gold' },
    '2': { text: '已确认', color: 'green' },
    '3': { text: '已取消', color: 'red' }
  };

  constructor(private http: _HttpClient, private msgSrv: NzMessageService, private cdr: ChangeDetectorRef) {
    this.loadCompanies();
    this.loadShops();
  }

  ngOnInit(): void {
    this.loadDataFromServer(this.pi, this.ps, this.q);
  }

  loadShops(companyID: number = 0): void {
    //let uri = `api/shop_map`;
    let uri = `api/shop_map_full`;
    this.http.get(uri, { companyId: companyID }).subscribe(res => {
      this.shops = res.data['shops'];
      for (let i = 0; i < this.shops.length; i++) {
        // @ts-ignore
        this.shopMap[this.shops[i]['shop_id']] = this.shops[i]['fordeal_shop_name'];
      }
    });
  }

  loadDataFromServer(pageIndex: number, pageSize: number, q: any) {
    this.loading = true;
    let params = new HttpParams().append('pi', `${pageIndex}`).append('ps', `${pageSize}`).appendAll(q);
    this.http.get(`${this.url}`, params).subscribe(res => {
      if (res.err_code != 0) {
        this.msgSrv.error(res.msg);
        return;
      }
      this.listOfData = res.data.list;
      this.total = res.data.total;
      this.loading = false;
    });
  }

  pageIndexChange(pageIndex: number) {
    this.loadDataFromServer(pageIndex, this.ps, this.q);
  }

  pageSizeChange(pageSize: number) {
    this.loadDataFromServer(this.pi, pageSize, this.q);
  }

  search() {
    this.loading = true;
    this.pi = 1;
    this.ps = 30;
    this.loadDataFromServer(this.pi, this.ps, this.q);
    this.loading = false;
  }

  companyList = [];
  loadCompanies(): void {
    this.http.get(`api/company_map`).subscribe(res => {
      this.companyList = res.data;
    });
  }
  companyChange(companyID: number) {
    this.loadShops(companyID);
    this.cdr.detectChanges();
  }
}
